# Compiler and tools
CC := gcc
RM := rm -rf
MKDIR := mkdir -p

# Compilation flags
CFLAGS := -Wall -Wextra -g -Iinclude

# Directory definitions
MAIN_SRC_DIR := test \
		   sources \


BUILD_DIR := build
#OBJ_DIR := $(BUILD_DIR)/obj
#EXE_DIR := $(BUILD_DIR)

# Final executable
obj ?= test

ifeq ($(obj),test)
	SRC_DIR = $(MAIN_SRC_DIR)
else
	SRC_DIR = $(obj)
endif


# Source files and object files
SRCS := $(shell find $(SRC_DIR) -name '*.c')
OBJS := $(patsubst %.c, %.o, $(SRCS))
OBJT := $(shell find . -name '*.o')

# Default target
all: out_$(obj).elf

# Link executable
out_$(obj).elf: $(OBJS) 
	@echo "\e[33m Linking $(BUILD_DIR)/$@ \e[0m"
	$(CC) $(CFLAGS) $^ -o $(BUILD_DIR)/$@
	@cp $(BUILD_DIR)/$@ ./
	@mv  $(OBJS)  $(BUILD_DIR)
	@echo "\e[32m Executable generated: $@ \e[0m"
	@echo ""

# Compile source files
%.o: %.c | $(BUILD_DIR)
	@echo "\e[33m Compiling: $< -> $@ \e[0m"
	$(CC) $(CFLAGS) -c $< -o $@
	
# Create necessary directories
$(BUILD_DIR):
	$(MKDIR) $@

# Clean target
.PHONY: clean
clean:
	$(RM) $(BUILD_DIR) out_*.elf $(OBJT)
	@echo  "\e[32m Clean complete \e[0m"
	@echo ""

.PHONY: help
help:
	@echo "Available commands:"
	@echo "  make       - Build project"
	@echo "  make clean - Clean generated files"
